package com.comum.javahomework420242025.controller;

import com.comum.javahomework420242025.pojo.Result;
import com.comum.javahomework420242025.pojo.User;
import com.comum.javahomework420242025.repository.UserRepository;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;

@RestController
public class LoginController {
    @Autowired
    private UserRepository userRepository;
    @PostMapping("/login")
    public Result login(@RequestBody User user, HttpServletRequest req){
        String account = user.getAccount();
        String pass = user.getPass();
        User datauser = userRepository.findByAccountAndPassAndType(account,pass);
        if(datauser==null)return Result.error("账号或密码错误！");
        if(!datauser.getType().equals(user.getType())) return Result.error("角色身份选择错误！");
        HttpSession session = req.getSession();
        String token = "poiuytrewqlkjhgfdsamnbvcxz";
        session.setAttribute("token",token);
        session.setAttribute("userid",datauser.getId());

        session.setMaxInactiveInterval(60*100); //6000,100min
        return Result.success(token);
    }
    @DeleteMapping("/logout")
    public Result logout(HttpServletRequest req){
        HttpSession session = req.getSession();
        session.removeAttribute("token");
        session.removeAttribute("userid");
        return Result.success();
    }
}
